// pages/shop/shop.js
var app = getApp()
Page({
  data: {
    cartList: [],
    imgUrls: [
      {
        link: '/pages/map/map',
        url: 'https://www.ymg3.com/ymgImage/Page/6.png'
      }, {
        link: '/pages/logs/logs',
        url: 'https://www.ymg3.com/ymgImage/Page/6.png'
      }, {
        link: '/pages/mine/mine',
        url: 'https://www.ymg3.com/ymgImage/Page/6.png'
      }
    ],
    hidden: false,
    nocancel: false,
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    circular: true,
    duration: 1000,
    chooseAddress: true,
    userInfo: {}
  }
  ,
  toshopdetail: function () {
    wx.navigateTo({
      url: '../shopDetail/shopDetail',
      success: function (res) {
        // success
      },
      fail: function (res) {
        // fail
      },
      complete: function (res) {
        // complete
      }
    })
  },
  onLoad: function (options) {
    //console.log("加载页面")
    var that=this;
   // wx.setStorageSync("isaddnewaddress", "22")//默认不新增地址
    this.getBackData();
    getBackDataSuperName(this);
    wx.getSystemInfo({//获取滑块的高宽
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
  },
  onReady: function () {
    //console.log("渲染页面")
    // 页面渲染完成
    getShipping(this)//获取配送费以及超市名称，并储存在本地
  },
  onShow: function () {
    //console.log("显示页面")
    // 页面显示
    if (wx.getStorageSync('cartLists')) {
      this.setData({
        cartList: wx.getStorageSync('cartLists'),
        proNum: wx.getStorageSync('cartLists').length
      })
    } else {
      this.setData({
        cartList: []
      })
    }
    wx.setStorageSync('cartLists', this.data.cartList)
    //console.log(this.data.cartList)
    //console.log(wx.getStorageSync('cartLists'))
  },
  onHide: function () {
    // 页面隐藏
  }

  , getBackData: function () { //超市首页加载得到超市商品信息
    var that = this;
     console.log(wx.getStorageSync('superID'))
    wx.request({
      url: app.globalData.allUrl + "/YMGW/superMarketAction/getSuperMarketIndex",
      method: 'GET',
      dataType: 'json',
      data: {
        superID: wx.getStorageSync('superID'),
        userId: wx.getStorageSync('userid')
      },
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        //console.log(res.data)
        if (res.data == 252) {
          wx.showToast({
            title: "附近没有超市或者该超市已冻结",
            icon: "loading"
          })
          setTimeout(function () {
            that.changeSuper()
          }, 2000)
        } else if (res.data == 251) {
          wx.showToast({
            title: "该超市暂停营业",
            icon: "loading"
          })
          setTimeout(function () {
            that.changeSuper()
          }, 2000)
        } else {
          that.setData({
            hotsList: res.data.hot,
            person: res.data.list,
          })
          wx.setStorageSync('superID', res.data.superId)
        }
      }
    })
  },
  sendCartProduct: function () {//将购物车里的商品储存在本地
    if (this.data.cartList != "") {
      wx.setStorageSync('cartLists', this.data.cartList)
    }
  },
  tosuperDetail:function(){
    wx.navigateTo({
      url: '../shopDetail/shopDetail',
    })
  },
  productDetail: function (e) {//点击单件商品跳转到详情页面
    // console.log(e.currentTarget.id)
    wx.navigateTo({
      url: '../productDetail/productDetail?id=' + e.currentTarget.id,
    })
  },
  changeSuper: function () {//换家超市，弹出选择从后台加载过来的以前超市地址，还可以添加新的超市（此时跳转到选地址页面)
    var that = this;
    
    wx.request({
      url: app.globalData.allUrl + "/YMGW/addressAction/getAddress",
      data: {
        userID: wx.getStorageSync('userid')
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
        console.log(res.data)
        var items1 = [];
        for (var x in res.data) {
          // items1.unshift({ name: res.data[x].latitudeNum + " " + res.data[x].longitudeNum, value: res.data[x].expressageAdd });
          items1.unshift({ name: res.data[x].id, value: res.data[x].expressageAdd });
        }

        that.setData({
          items: items1,
        })
      }
    })
    this.setData({
      chooseAddress: false
    })
  },
  radioChange: function (e) {//储存选择地址的经纬度
    // var lonAndlat = e.detail.value.split(" ")
    this.setData({
      // lonAndlat0: lonAndlat[1],
      // lonAndlat1: lonAndlat[0],
      ischoose: true
    })
    wx.setStorageSync('haddressID',e.detail.value);
    wx.request({
      url: app.globalData.allUrl + "/YMGW/addressAction/getAddressOne",
      data: {
        addID: e.detail.value
      },
      method: 'GET',
      success: function (res) {
        wx.setStorageSync('superID', res.data.superId);
      }
    })
    wx.setStorageSync("isaddnewaddress", "22")//默认不新增地址
    //console.log(lonAndlat)
  },
  chooseaddress: function () {//点击选地址的确认按钮
    var that = this;
    app.inputUser = ""//  清空本地地址
    wx.setStorageSync('addressID', "")//  清空本地地址
    this.setData({
      chooseAddress: true
    })
    // console.log(that.data.lonAndlat0)
    if (that.data.ischoose) {
      // console.log("dssdfsd")
      // wx.request({//将经纬度发送到后台并且从后台获取到对应的超市id以及超市名称
      //   url: app.globalData.allUrl + "/YMGW/superMarketAction/skipPrefecture",
      //   data:
      //   {
      //     lon: that.data.lonAndlat0,
      //     lat: that.data.lonAndlat1
      //   },
      //   method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      //   // header: {}, // 设置请求的 header
      //   success: function (res) {
      //     //console.log(res.data)
      //     if (res.data != null) {
      //       wx.setStorageSync('superID', res.data.id);
      //       wx.setStorageSync('superName', res.data.name);
      //       // getPersonSuperInfo(that);
      //       wx.redirectTo({
      //         url: '/pages/shop/shop',
      //       });
      //       wx.setStorageSync('cartLists', "")
      //     } else {
      //       // console.log("设置超市信息失败")
      //     }
      //   }
      // })
      wx.redirectTo({
        url: '/pages/shop/shop',
      });
      wx.setStorageSync('cartLists', "")
    }
  },
  cancelchoose: function () {//点击选地址的取消按钮
    this.setData({
      chooseAddress: true
    })
  },
  sendMsgToBuy: function (e) {//获取用户所选中产品的详细信息
    var that = this;
    
    if (that.data.cartList.length > 0) {
      var config = false;
      for (var x in that.data.cartList) {
        if (that.data.cartList[x].productId == e.target.dataset.id) {
          if (that.data.cartList[x].quantity == that.data.cartList[x].repertory) {//如果增加的数量大于库存，则取消增加；
            wx.showToast({
              title: "库存不足",
              icon: "loading"
            })
          } else {
            that.data.cartList[x].quantity += 1;
          }
          config = true;
        }
      }
     
      if (!config) {
        getCartInfo(that, e)//加入购物车
      }
    } else {
      getCartInfo(that, e)//加入购物车
    }
    wx.setStorageSync('cartLists', this.data.cartList)
    that.setData({
      proNum: wx.getStorageSync('cartLists').length
    })
    
  },
  newAddAddress: function () {//点击新增收货地址后弹出选地址页面
    moveToMap(this)//调用地图
  },

  sendMsgToCart: function (e) {//点击加入购物车时将数据添加至购物车
    var that = this;
    if (that.data.cartList.length > 0) {
      var config = false;
      for (var x in that.data.cartList) {
        if (that.data.cartList[x].productId == e.target.dataset.id) {
          if (that.data.cartList[x].quantity == that.data.cartList[x].repertory) {//如果增加的数量大于库存，则取消增加；
            wx.showToast({
              title: "库存不足",
              icon: "loading"
            })
          } else {
            that.data.cartList[x].quantity += 1;
            
            wx.showToast({
               title: "已加入购物车"
            })
          }
          config = true;
        }
      }
      if (!config) {
        getCartInfo(that, e)//加入购物车
        wx.showToast({
           title: "已加入购物车"

        })
      }
    } else {
      getCartInfo(that, e)//加入购物车
      wx.showToast({
         title: "已加入购物车"

      })
    }
    wx.setStorageSync('cartLists', this.data.cartList)
    that.setData({
      proNum: wx.getStorageSync('cartLists').length
    })
  }
})
function getBackDataSuperName(that) {//同步加载本地储存超市名字

  //console.log(res.data)
  that.setData({
    superName: wx.getStorageSync('superName')
  })
  app.superName = wx.getStorageSync('superName')
}
function getCartInfo(that, e) {//加入购物车，将商品信息储存在
  //console.log(that.data.cartList)
  var CartName = e.target.dataset.name;
  var CartPrice = e.target.dataset.price;
  var CartID = e.target.dataset.id;
  var CartSuper = e.target.dataset.name;
  var Cartquantity = 1;
  var totalPrices = "";
  var Cartimg = e.target.dataset.img
  var Cartrepertory = e.target.dataset.repertory
  var carts = { productName: CartName, unitPrice: CartPrice, productId: CartID, quantity: Cartquantity, totalPrices: totalPrices, repertory: Cartrepertory, img: Cartimg}
  that.data.cartList.push(carts);
}



function moveToMap(that) {
  wx.chooseLocation({//调用地图，并将得到的地址发送至后台返回超市对象
    success: function (res) {
           //console.log(res)
      that.setData({
        address: res.address,
        OL: res.longitude + ":" + res.latitude,
        lon: res.longitude,
        lat: res.latitude
        // lon: 104.104561,
        // lat: 30.714233
      });
      app.longitude = res.longitude;
      app.latitude = res.latitude;
      var addresses=res.address;
      wx.setStorageSync('longitude', res.longitude)
      wx.setStorageSync('latitude', res.latitude)
      wx.request({//将经纬度发送到后台并且从后台获取到对应的超市id以及超市名称
        url: app.globalData.allUrl + "/YMGW/superMarketAction/skipPrefecture",
        data:
        {
          lon: that.data.lon,
          lat: that.data.lat
        },
        method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        // header: {}, // 设置请求的 header
        success: function (res) {
          if (res.data != null) {
            wx.setStorageSync('superID', res.data.id);
            wx.setStorageSync('superName', res.data.name);
            // getPersonSuperInfo(that);
            wx.setStorageSync('addressID', "")
            wx.setStorageSync("isaddnewaddress", "11")//只要换了定位都能新增地址
            app.inputUser = ""
            wx.redirectTo({
              url: '/pages/shop/shop',
            })
            wx.showToast({
              title: '换家超市成功',
              icon: 'success',
              duration: 2000
            })
            // getStreet(that)//获取街道名称
            app.addressDetailes=addresses
          } else {
            wx.showToast({
              title: '附近没有超市，请重新选择!',
              icon: 'success',
              duration: 3000
            })
          }
        }
      })
    }
  })
}



function getShipping(that) {//获取配送费
  //  console.log(wx.getStorageSync('superID'))
  wx.request({
    url: app.globalData.allUrl + "/YMGW/productaAction/getSupermarketSet",
    data: {
      superID: wx.getStorageSync('superID')
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    // header: {}, // 设置请求的 header
    success: function (res) {
      // success
      // console.log(res.data)
      if (res.data) {
        wx.setStorageSync('superShipping', res.data.sendMoney)
        wx.setStorageSync('upSendMoney', res.data.upSendMoney)
        that.setData({
          superName: res.data.superName
        })
      }
    }
  })
}



function getStreet(that) {//获取街道名称
  wx.request({
    url: app.globalData.allUrl + "/YMGW/utilAction/getmapinfo",
    data: {
      latitude: that.data.lat,
      longitude: that.data.lon
    },
    success: function (ops) {
      //console.log(ops.data)
      var newJson = ops.data.indexOf("{")
      var nextJson = ops.data.lastIndexOf(")")
      var userJson = ops.data.substring(newJson, nextJson)
      var res = JSON.parse(userJson)
      //console.log(res);
      var addressDetaile = res.result.addressComponent.province + res.result.addressComponent.city + res.result.addressComponent.district + res.result.addressComponent.street
      app.addressDetailes = addressDetaile;
      app.district = res.result.addressComponent.district
      // console.log( app.addressDetailes)
      //  wx.setStorageSync('adcode', res.result.addressComponent.adcode)
    }
  })
}